/*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Universite de Sherbrooke nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <QApplication>
#include <QtCore/QDir>
#include "rtabmap/utilite/UEventsManager.h"
#include "rtabmap/core/RtabmapThread.h"
#include "rtabmap/core/Rtabmap.h"
#include "rtabmap/gui/MainWindow.h"
#include <QMessageBox>
#include "rtabmap/utilite/UObjDeletionThread.h"
#include "rtabmap/utilite/UFile.h"
#include "rtabmap/utilite/UConversion.h"
#include "ObjDeletionHandler.h"

using namespace rtabmap;

/*
 * 这个程序是基于事件驱动的，
 * TODO:事件驱动的机制，主要相关的类，把这些类和slam的功能分开并联系起来
 * 整个事件的收集和分发都是由 UEventManager来处理的
 */

int main(int argc, char* argv[])
{
	/* Set logger type */
	ULogger::setType(ULogger::kTypeConsole);
	ULogger::setLevel(ULogger::kInfo);
  
	/* Create tasks */
	/*
	 * 这段代码将mainwindow的事件交给QApplication处理
	 * mainwindow的作用：显示的主界面，用于交互和显示
	 */
	QApplication * app = new QApplication(argc, argv);
	MainWindow * mainWindow = new MainWindow();
	app->installEventFilter(mainWindow); // to catch FileOpen events.
    
	/*
	 * 读取已经存在的数据库：
	 * 数据库：存储上次运行的相关数据：主要包括？
	 */
	std::string database;
	for(int i=1; i<argc; ++i)
	{
	    std::string value = uReplaceChar(argv[i], '~', UDirectory::homeDir());
	    if(UFile::exists(value) &&
	      UFile::getExtension(value).compare("db") == 0)
	    {
			database = value;
			break;
	    }
	}

	UINFO("Program started...");

	/*
	 * 增加事件处理的handler,但是事件是怎么接受并分发的呢？
	 * 将事件分发给主显示界面mainwindow
	 */
	UEventsManager::addHandler(mainWindow);

	/* Start thread's task */
	if(mainWindow->isSavedMaximized())
	{
		mainWindow->showMaximized();
	}
	else
	{
		mainWindow->show();
	}
	
	/*
	 * rtabmap是处理的核心程序
	 */
	
	RtabmapThread * rtabmap = new RtabmapThread(new Rtabmap());
	rtabmap->start(); // start it not initialized... will be initialized by event from the gui
	
	/*
	 * 将事件分发给核心处理程序rtabmap
	 */
	UEventsManager::addHandler(rtabmap);
	
	/*
	 * rtabmap是后端处理程序，mainwindow是前端显示程序，两者需要通过UEventsManager来进行通信
	 */
    
	if(!database.empty())
	{
	    QMetaObject::invokeMethod(mainWindow, "openDatabase", Qt::QueuedConnection, Q_ARG(QString, QString(database.c_str())));
	}

	// Now wait for application to finish
	app->connect( app, SIGNAL( lastWindowClosed() ),
				app, SLOT( quit() ) );
	
	/*
	 * 这个程序会一直执行，直到用户退出
	 */
	app->exec();// MUST be called by the Main Thread

	
	/*
	 * 程序已经退出，完成程序的退出工作
	 */
	/* Remove handlers */
	UEventsManager::removeHandler(mainWindow);
	UEventsManager::removeHandler(rtabmap);

	UINFO("Killing threads...");
	rtabmap->join(true);

	UINFO("Closing RTAB-Map...");
	delete rtabmap;
	delete mainWindow;
	delete app;
	UINFO("All done!");

	return 0;
}
